import Observer from './Observer';

class ObserverList {
    observerList: Array<Observer>;       //observer list

    constructor() {
        this.observerList = [];
    }

    // add observer
    add(observer: Observer) {
        this.observerList.push(observer);
    }

    // clear observer
    empty() {
        this.observerList = [];
    }

    // ObserverList's count
    count(): number {
        return this.observerList.length;
    }

    // get observer by index
    get(index: number): Observer {
        if(index >= 0 && index < this.observerList.length) {
            return this.observerList[index];
        }
    }

    // insert observer
    insert(observe: Observer, index: number) {
        index = index > 0 ? index : 0;
        index = index <= this.observerList.length ? index : this.observerList.length;

        this.observerList.splice(index, 0, observe);
    }

    // find observer
    indexOf(observer: Observer, startIndex?: number): number {
        let pointer = -1, i = startIndex || 0;

        while(i < this.observerList.length) {
            if(this.observerList[i] === observer) {
                pointer = i;
                break;
            }

            i++;
        }

        return pointer;
    }

    removeIndexAt(index: number) {
        if(index >= 0 && index < this.observerList.length) {
            this.observerList.splice(index, 1);
        }
    }
}

export default ObserverList;